package com.zzptc.myapp1130bookreader.ui.dashboard;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.zzptc.myapp1130bookreader.Adapter.BookAdapter;
import com.zzptc.myapp1130bookreader.Bean.Book;
import com.zzptc.myapp1130bookreader.Bean.ChooseBook;
import com.zzptc.myapp1130bookreader.R;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

public class DashboardFragment extends Fragment {
    private ListView chooselv;
    List<Book> bookList=new ArrayList<>();
    BookAdapter adapter;
    List<ChooseBook>chooseBookList=new ArrayList<>();

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_dashboard, container, false);

        initView(view);
        initData();
        setListener();
        return view;

    }

    private void setListener() {
        chooselv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
              int cid =  chooseBookList.get(i).getId();
              LitePal.delete(ChooseBook.class,cid);
              chooseBookList.remove(i);
              bookList.remove(i);
              adapter.notifyDataSetChanged();
              showToast("已取消收藏");
                return false;
            }
        });
    }

    private void initData() {
        SharedPreferences sp=getActivity().getSharedPreferences("userinfo", Context.MODE_PRIVATE);
        int uid=sp.getInt("userid",-1);

        chooseBookList= LitePal.
                where("userid=?",uid+" ").find(ChooseBook.class);
        for (ChooseBook c:chooseBookList){  //收藏的
        for (Book b:LitePal.findAll(Book.class)){ //自由顺序
            if (b.getId()==c.getBookid())
                bookList.add(b);
            }
        }
    }

    private void initView(View view) {
        chooselv=view.findViewById(R.id.chooselv);
        adapter=new BookAdapter(getContext(),R.layout.book_item,bookList);
        chooselv.setAdapter(adapter);

    }
    private void showToast(String str){
        Toast.makeText(getContext(),str,Toast.LENGTH_SHORT).show();
    }
}